package com.xielx.httpclikent.util;

import com.xielx.httpclikent.MyHttpClient;
import com.xielx.httpclikent.bean.MyHttpGet;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Image;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

public class ImageNetWork {
    private final static HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0, "HmOSImageLoader");
    private AbilitySlice slice;
    private Image image;
    private  String url;

    public ImageNetWork(AbilitySlice abilitySlice, Image image, String url) {
        this.slice = abilitySlice;
        this.image = image;
        this.url = url;
    }

    public static ImageNetWork show(AbilitySlice abilitySlice, Image image, String url){
        ImageNetWork bean = new ImageNetWork(abilitySlice, image, url);
        bean.show();
        return bean;
    }

    public void show(){
        HiLog.debug(LABEL_LOG,"show the image[%{public}s]",url);
        MyHttpClient client = MyHttpClient.getInstance(slice);
        MyHttpGet get = new MyHttpGet(url);
        client.asyncDoRequest(get,response -> {
            ImageSource is = ImageSource.create(response.getContent(),null);
            PixelMap pixelMap = is.createPixelmap(null);
            slice.getUITaskDispatcher().asyncDispatch(()->{
                image.setPixelMap(pixelMap);
                pixelMap.release();
            });
        });
    }
}
